// collectpage.js
// 获取app实例
const app = getApp();

Page({
  data: {
    showmsg: false,
    totalHeaderHeightall: "",
    collectKnowledgePoints: [], // 用户收藏的知识点列表
    loading: false,
    cancelCollectid: "",
    showtan: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function () {
    this.setData({
      totalHeaderHeightall: app.globalData?.totalHeaderHeight
    });
    // 加载用户收藏的知识点
    this.loadCollectKnowledgePoints();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // 每次显示页面时重新加载收藏列表
    this.loadCollectKnowledgePoints();
  },

  /**
   * 加载用户收藏的知识点列表
   */
  loadCollectKnowledgePoints: function () {
    this.setData({ loading: true });

    // 检查用户是否登录
    const userToken = wx.getStorageSync('userToken');
    if (!userToken) {
      wx.showModal({
        title: '提示',
        content: '请先登录后再查看收藏列表',
        showCancel: false,
        success: function (res) {
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/login/login'
            });
          }
        }
      });
      this.setData({ loading: false });
      return;
    }

    // 调用API获取用户收藏的知识点
    app.api.getUserFavorites().then(res => {
      if (res && res.code === 200 && res.data && Array.isArray(res.data)) {
        this.setData({
          collectKnowledgePoints: res.data
        });

        // 如果收藏列表为空，显示提示
        if (res.data.length === 0) {


          this.setData({
            showmsg: true,
            massges: "暂无收藏的知识点",
          });
          setTimeout(() => {
            this.setData({
              showmsg: false,
              massges: "暂无收藏的知识点",
            });
          }, 1000);
        }
      } else {
        this.setData({
          collectKnowledgePoints: []
        });
        this.setData({
          showmsg: true,
          massges: "获取收藏列表失败",
        });
        setTimeout(() => {
          this.setData({
            showmsg: false,
            massges: "获取收藏列表失败",
          });
        }, 1000);
      }
    }).catch(err => {
      console.error('获取收藏列表失败:', err);
      this.setData({
        collectKnowledgePoints: []
      });
      wx.showToast({
        title: '网络异常，请稍后重试',
        icon: 'none'
      });
    }).finally(() => {
      this.setData({ loading: false });
      wx.hideLoading();
    });
  },

  /**
   * 点击收藏知识点跳转到详情页面
   */
  onCollectItemTap: function (e) {
    const knowledgeId = e.currentTarget.dataset.id;
    const knowledge = this.data.collectKnowledgePoints.find(k => k.id === knowledgeId);

    if (!knowledge) return;

    wx.navigateTo({
      url: `/pages/knowledge/detail?id=${knowledgeId}`
    });
  },

  clearthis() {
    this.setData({
      showtan: false
    })
  },
  /**
   * 取消收藏知识点
   */
  queren() {
    // 调用取消收藏API
    app.api.toggleFavorite({
      knowledgePointId: this.data.cancelCollectid,
      status: 0
    }).then(res => {
      wx.hideLoading();
      if (res && res.code === 200) {
        // wx.showToast({
        //   title: '取消收藏成功',
        //   icon: 'success'
        // });
        this.setData({
          showtan: false
        })
        // 重新加载收藏列表
        this.loadCollectKnowledgePoints();
      } else {
        wx.showToast({
          title: '取消收藏失败',
          icon: 'none'
        });
      }
    }).catch(err => {
      wx.hideLoading();
      console.error('取消收藏失败:', err);
      wx.showToast({
        title: '操作失败，请稍后重试',
        icon: 'none'
      });
    });
  },
  cancelCollect: function (e) {
    const knowledgeId = e.currentTarget.dataset.id;

    this.setData({
      cancelCollectid: e.currentTarget.dataset.id,
      showtan: true
    })
    // wx.showModal({
    //   title: '确认取消收藏',
    //   content: '确定要取消收藏该知识点吗？',
    //   success: (res) => {
    //     if (res.confirm) {
    //     }
    //   }
    // });
  }
});
